﻿using System;
using System.IO;
using BingoServerCommon.Db.Pool;
using BingoServerCommon.Log4net;
using Newtonsoft.Json;

namespace BingoServerCommon.Db
{
	#region jsonConfigFile Class

	public class Rootobject
	{
		public Connectionstring[] connectionStrings { get; set; }
	}

	public class Connectionstring
	{
		public string name { get; set; }
		public string connectionString { get; set; }
		public string providerName { get; set; }
	}

	#endregion

	#region Mysql Init

	public class MysqlInit
	{
		/// <summary>
		/// 统一的，数据库的数目
		/// </summary>
		public static int DbNum = 3;

		/// <summary>
		/// 
		/// </summary>
		public static Rootobject RootObject = null;

		#region MyRegion

		/// <summary>
		/// data_conn
		/// </summary>
		public static string BingoDataMysqlConnectionStr
		{
			get
			{
				if (RootObject == null || RootObject.connectionStrings.Length != DbNum)
				{
					return string.Empty;
				}

				var dataConfig = RootObject.connectionStrings[0];
				return dataConfig.connectionString;
			}
		}


		/// <summary>
		/// config_conn
		/// </summary>
		public static string BingoConfigMysqlConnectionStr
		{
			get
			{
				if (RootObject == null || RootObject.connectionStrings.Length != DbNum)
				{
					return string.Empty;
				}

				var dataConfig = RootObject.connectionStrings[1];
				return dataConfig.connectionString;
			}
		}



		/// <summary>
		/// erp_conn
		/// </summary>
		public static string BingoErpMysqlConnectionStr
		{
			get
			{
				if (RootObject == null || RootObject.connectionStrings.Length != DbNum)
				{
					return string.Empty;
				}

				var dataConfig = RootObject.connectionStrings[2];
				return dataConfig.connectionString;
			}
		}

		#endregion



		/// <summary>
		/// 
		/// </summary>
		public static ConnectionPool Init()
		{
			try
			{
				//初始化配置
				var fileContent = File.ReadAllText(Path.Combine("Db", "MysqlConfig" + ".json"));
				//var str = Regex.Replace(fileContent, @"/\*[\s|\S]*?\*/", "");	//如果转换有报错，则可取消此行注释

				var obj = JsonConvert.DeserializeObject<Rootobject>(fileContent);

				//return obj;
				RootObject = obj;

				//初始化连接池
				string strcon = BingoDataMysqlConnectionStr;
				ConnectionPool tmpPool = new ConnectionPool(strcon);
				tmpPool.createPool();
				return tmpPool;
			}
			catch (Exception e)
			{
				LogHelper.WriteFatal("MysqlInit.Init", e);
				return null;
			}
		}



	}

	#endregion
}
